package com.example.springboot.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.controller.dto.ArticleDTO;
import com.example.springboot.entity.Announcements;
import com.example.springboot.entity.Articles;
import com.example.springboot.entity.Likes;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.ArticlesMapper;
import com.example.springboot.mapper.LikesMapper;
import com.example.springboot.service.IArticlesService;
import com.example.springboot.service.ILikesService;
import com.example.springboot.service.IUserService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章表 API控制器 - 不需要token验证的API
 * </p>
 *
 * @author
 */
@RestController
@RequestMapping("/api/articles")
public class ArticlesApi {

    @Resource
    private IArticlesService articlesService;

    @Resource
    private ILikesService likesService;

    @Resource
    private LikesMapper likesMapper;

    @Resource
    private ArticlesMapper articlesMapper;
    @Resource
    private IUserService iUserService;

    //获取文章
    @GetMapping("/list")
    public Result list() {
        List<Articles> articlesList = articlesService.list();
        List<ArticleDTO> resultList = articlesList.stream().map(article -> {
            ArticleDTO dto = new ArticleDTO();
            // 复制相同字段（避免手动 set）
            BeanUtils.copyProperties(article, dto);

            // 查询并设置作者信息
            User author = iUserService.getById(article.getAuthorId());
            if (author != null) {
                dto.setAvatar(author.getAvatarUrl());
                dto.setNickName(author.getNickname());
            }
            return dto;
        }).collect(Collectors.toList());

        return Result.success(resultList);
    }

    //获取文章详情
    @GetMapping("/detail/{id}")
    public Result selectDetails(@PathVariable Integer id) {
        // 1. 查询文章
        Articles article = articlesService.getById(id);
        if (article == null) {
            return Result.success("文章不存在");
        }

        // 2. 转换为 DTO
        ArticleDTO dto = new ArticleDTO();
        BeanUtils.copyProperties(article, dto);

        // 3. 查询作者信息
        User author = iUserService.getById(article.getAuthorId());
        if (author != null) {
            dto.setAvatar(author.getAvatarUrl());
            dto.setNickName(author.getNickname());
        }

        // 4. 返回单条数据
        return Result.success(dto);
    }
    //相关推荐
    @GetMapping("/related")
    public Result related(@RequestParam String categoryId) {
        QueryWrapper<Articles> articlesQueryWrapper = new QueryWrapper<>();
        //状态为1 才能展示
        articlesQueryWrapper.eq("status",1);

        //筛选分类
        if (StringUtils.isNotBlank(categoryId) && !"0".equals(categoryId)) {
            articlesQueryWrapper.eq("category_id",categoryId);
        }
        //查询出文章和对应的作者的个人信息
        List<Articles> articlesList = articlesService.list(articlesQueryWrapper);
        List<ArticleDTO> resultList = articlesList.stream().map(article -> {
            ArticleDTO dto = new ArticleDTO();
            // 复制相同字段（避免手动 set）
            BeanUtils.copyProperties(article, dto);

            // 查询并设置作者的个人信息，名称和头像
            User author = iUserService.getById(article.getAuthorId());
            if (author != null) {
                dto.setAvatar(author.getAvatarUrl());
                dto.setNickName(author.getNickname());
            }
            return dto;
        }).collect(Collectors.toList());
        Collections.shuffle(resultList); // 打乱列表顺序
        List<ArticleDTO> randomArticles = resultList.subList(0, 6); // 取前6篇
        return Result.success(randomArticles);
    }

    //个人主页文章
    @GetMapping("/personal")
    public Result personal(@RequestParam String authorId) {
        QueryWrapper<Articles> articlesQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(authorId) && !"0".equals(authorId)) {
            articlesQueryWrapper.eq("author_id",authorId);
        }
        //查询出文章和对应的作者的个人信息
        List<Articles> articlesList = articlesService.list(articlesQueryWrapper);
        List<ArticleDTO> resultList = articlesList.stream().map(article -> {
            ArticleDTO dto = new ArticleDTO();
            // 复制相同字段（避免手动 set）
            BeanUtils.copyProperties(article, dto);

            // 查询并设置作者信息
            User author = iUserService.getById(article.getAuthorId());
            if (author != null) {
                dto.setAvatar(author.getAvatarUrl());
                dto.setNickName(author.getNickname());
            }
            return dto;
        }).collect(Collectors.toList());

        return Result.success(resultList);
    }

    //最新发布分页
    @GetMapping("/page")
    public Result findPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam String categoryId) {

        // 构造分页和排序条件
        Page<ArticleDTO> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<Articles>();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("status",1);
        if (StringUtils.isNotBlank(categoryId) && !"0".equals(categoryId)) {
            queryWrapper.eq("category_id",categoryId);
        }
        // 执行查询（自动关联用户表）
        Page<ArticleDTO> result = articlesService.pageWithAuthor(pageInfo, queryWrapper);
        return Result.success(result);
    }


    //个人主页文章
    @GetMapping("/personal/page")
    public Result personalPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam String authorId) {

        // 构造分页和排序条件
        Page<ArticleDTO> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<Articles>();
        queryWrapper.orderByDesc("id");
        if (StringUtils.isNotBlank(authorId) && !"0".equals(authorId)) {
            queryWrapper.eq("author_id",authorId);
        }
        // 执行查询（自动关联用户表）
        Page<ArticleDTO> result = articlesService.pageWithAuthor(pageInfo, queryWrapper);
        return Result.success(result);
    }

    //热门推荐
    @GetMapping("/randomList")
    public Result randomList() {
        // 获取所有文章列表
        List<Articles> allArticles = articlesMapper.selectlist();

        // 如果文章数量小于等于6，直接返回所有
        if (allArticles.size() <= 6) {
            return Result.success(allArticles);
        }

        // 随机选择6篇文章
        Collections.shuffle(allArticles); // 打乱列表顺序
        List<Articles> randomArticles = allArticles.subList(0, 6); // 取前6篇

        return Result.success(randomArticles);
    }

    //搜索
    @GetMapping("/search/page")
    public Result searchPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam String title) {

        // 构造分页和排序条件
        Page<ArticleDTO> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",1);
        //可以根据标题、内容、内容摘要、标签、作者id来查询
        if (!"".equals(title)) {
            queryWrapper.and(wrapper ->
                    wrapper.like("title", title)
                            .or()
                            .like("content", title)
                            // 可以继续添加其他需要查询的字段
                            .or()
                            .like("summary", title)
                            .or()
                            .like("author_id",title)
                            .or()
                            .like("tags",title)

            );
        }

        // 执行查询（自动关联用户表）
        Page<ArticleDTO> result = articlesService.pageWithAuthor(pageInfo, queryWrapper);
        return Result.success(result);
    }


    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(articlesService.getById(id));
    }


    @GetMapping("/category/{categoryId}")
    public Result getByCategoryId(@PathVariable Integer categoryId) {
        QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        return Result.success(articlesService.list(queryWrapper));
    }

    //浏览量加1
    @PostMapping("/view/{categoryId}")
    public Result getViews(@PathVariable Integer categoryId) {
        articlesService.updateView(categoryId);
        return Result.success();
    }

    // 新增点赞和点赞加1
    @PostMapping("/like")
    public Result save(@RequestBody Likes likes) {
        // 设置当前时间为点赞时间
        likes.setTime(LocalDateTime.now());  // 使用LocalDateTime记录精确时间

        try {
            likesService.saveOrUpdate(likes);
            // 传入点赞文章的id去增加点赞数
            articlesMapper.updateLike(likes.getArticleId());

            // 格式化时间用于返回给前端 (格式示例：12:30:45)
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            String formattedTime = likes.getTime().format(formatter);

            return Result.success("点赞成功，时间：" + formattedTime);
        } catch (Exception e) {
            return Result.error("500","点赞失败：");
        }
    }

    // 删除点赞和点赞-1
    @PostMapping("/unLike")
    public Result deleteLikes(@RequestBody Likes likes) {
       articlesMapper.deleteisLikesById(likes.getArticleId(), likes.getUserId());
        //传入点赞文章的id去增加点赞数
        articlesMapper.updateUnLike(likes.getArticleId());
        return Result.success();
    }

    //是否点赞
    @PostMapping("/isLike")
    public Result isLike(@RequestBody Likes likes) {
        // 参数校验
        if (likes.getArticleId() == null || likes.getUserId() == null) {
            return Result.error("500","文章ID和用户ID不能为空");
        }

        try {
            // 查询点赞记录
            Integer count = articlesMapper.selectisLikes(likes.getArticleId(), likes.getUserId());

            // 返回结果
            // 假设 selectisLikes 返回的是记录数(0表示未点赞，1表示已点赞)
            boolean isLiked = count != null && count > 0;

            return Result.success(isLiked);

        } catch (Exception e) {
            return Result.error("500","点赞过了");
        }
    }

    // 发布文章
    @PostMapping("/add")
    public Result save(@RequestBody Articles articles) {

        articlesService.saveOrUpdate(articles);
        return Result.success();
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        articlesMapper.deleteById(id);
        return Result.success();
    }
}
